package com.linjiang.protocol;

import com.linjiang.common.Invocation;
import com.linjiang.register.LocalRegister;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class HttpServerHandler {

    /**
     * 处理请求
     * @param req
     * @param res
     */
    public void handler(ServletRequest req, ServletResponse res){
        // 处理请求 --> 接口、方法、方法参数
        try {
            //反序列化 获取invocation对象，获取接口、方法、方法等参数
            Invocation invocation = (Invocation) new ObjectInputStream(req.getInputStream()).readObject();
            System.out.println("接收到请求："+invocation);
            String interfaceName = invocation.getInterfaceName();
            String version = invocation.getVersion();
            //基于接口名和版本号，获取对应的实现类
            Class impClass = LocalRegister.getMap(interfaceName+version);
            //根据请求的方法名和方法参数类型，获取接口实现类中的对应方法
            Method method = impClass.getMethod(invocation.getMethodName(), invocation.getParameterType());
            //传入方法参数，执行接口实现类的方法，获得执行结果
            String invokeResult = (String) method.invoke(impClass.newInstance(), invocation.getParameters());
            //写入返回接口
            IOUtils.write(invokeResult, res.getOutputStream());
        } catch (IOException | ClassNotFoundException | NoSuchMethodException | IllegalAccessException |
                 InvocationTargetException | InstantiationException e) {
            throw new RuntimeException(e);
        }
    }
}
